<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-indigo-50 flex items-center justify-center px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
      <!-- Logo 和标题 -->
      <div class="text-center">
        <div class="mx-auto h-16 w-16 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-full flex items-center justify-center">
          <el-icon :size="28" class="text-white">
            <User />
          </el-icon>
        </div>
        <h2 class="mt-6 text-3xl font-bold text-gray-900">欢迎回来</h2>
        <p class="mt-2 text-sm text-gray-600">登录到您的AI角色扮演账户</p>
      </div>

      <!-- 登录表单 -->
      <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-8">
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          size="large"
          @submit.prevent="handleSubmit"
        >
          <!-- 账号输入 -->
          <el-form-item prop="account">
            <el-input
              v-model="loginForm.account"
              placeholder="用户名 / 邮箱 / 手机号"
              :prefix-icon="User"
              clearable
              class="h-12"
            />
          </el-form-item>

          <!-- 密码输入 -->
          <el-form-item prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              :prefix-icon="Lock"
              show-password
              clearable
              class="h-12"
              @keyup.enter="handleSubmit"
            />
          </el-form-item>

          <!-- 记住我和忘记密码 -->
          <div class="flex items-center justify-between mb-6">
            <el-checkbox v-model="loginForm.rememberMe" class="text-sm text-gray-600">
              记住我
            </el-checkbox>
            <router-link
              to="/reset-password"
              class="text-sm text-blue-600 hover:text-blue-500 transition-colors"
            >
              忘记密码？
            </router-link>
          </div>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button
              type="primary"
              size="large"
              :loading="loading"
              @click="handleSubmit"
              class="w-full h-12 text-base font-medium"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 分割线 -->
        <div class="relative my-6">
          <div class="absolute inset-0 flex items-center">
            <div class="w-full border-t border-gray-300" />
          </div>
          <div class="relative flex justify-center text-sm">
            <span class="px-2 bg-white text-gray-500">或者</span>
          </div>
        </div>

        <!-- 注册链接 -->
        <div class="text-center">
          <span class="text-sm text-gray-600">还没有账户？</span>
          <router-link
            to="/register"
            class="ml-1 text-sm text-blue-600 hover:text-blue-500 font-medium transition-colors"
          >
            立即注册
          </router-link>
        </div>
      </div>

      <!-- 快速登录 -->
      <div class="bg-white rounded-xl shadow-lg border border-gray-100 p-6">
        <h3 class="text-center text-sm font-medium text-gray-700 mb-4">快速体验</h3>
        <div class="flex justify-center">
          <el-button
            size="small"
            class="w-full max-w-xs"
            @click="quickLogin('demo')"
            :loading="quickLoginLoading"
          >
            <el-icon class="mr-1"><User /></el-icon>
            演示账户
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { validators } from '@/utils/auth'
import type { LoginForm } from '@/types'

// 路由和状态
const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// 表单引用
const loginFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)
const quickLoginLoading = ref(false)

// 表单数据
const loginForm = reactive<LoginForm>({
  account: '',
  password: '',
  rememberMe: false
})

// 表单验证规则
const loginRules: FormRules = {
  account: [
    {
      required: true,
      message: '请输入用户名、邮箱或手机号',
      trigger: 'blur'
    },
    {
      min: 3,
      message: '账号长度不能少于3个字符',
      trigger: 'blur'
    },
    {
      validator: (rule, value, callback) => {
        if (!validators.account(value)) {
          callback(new Error('请输入有效的用户名、邮箱或手机号'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    },
    {
      min: 6,
      message: '密码长度不能少于6个字符',
      trigger: 'blur'
    }
  ]
}

/**
 * 处理表单提交
 */
const handleSubmit = async () => {
  if (!loginFormRef.value) return

  try {
    // 表单验证
    await loginFormRef.value.validate()
    
    loading.value = true

    // 执行登录
    await authStore.login(loginForm)

    // 登录成功，等待状态更新后跳转
    await nextTick()
    const redirect = (route.query.redirect as string) || '/chat'
    
    // 确保认证状态已更新
    if (authStore.isAuthenticated) {
      await router.push(redirect)
    } else {
      // 如果状态还没更新，等待一下再跳转
      setTimeout(async () => {
        await router.push(redirect)
      }, 100)
    }

  } catch (error) {
    // 错误处理已在store中完成
    console.error('Login failed:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 快速登录
 */
const quickLogin = async (type: 'demo') => {
  try {
    quickLoginLoading.value = true

    const quickLoginData: LoginForm = {
      account: 'ceshi',
      password: 'w12345678',
      rememberMe: false
    }

    // 填充表单（仅用于演示）
    Object.assign(loginForm, quickLoginData)

    // 执行登录
    await authStore.login(quickLoginData)

    // 成功提示
    ElMessage.success('演示账户登录成功')

    // 登录成功，等待状态更新后跳转
    await nextTick()
    const redirect = (route.query.redirect as string) || '/chat'
    
    // 确保认证状态已更新
    if (authStore.isAuthenticated) {
      await router.push(redirect)
    } else {
      // 如果状态还没更新，等待一下再跳转
      setTimeout(async () => {
        await router.push(redirect)
      }, 100)
    }

  } catch (error) {
    ElMessage.error('演示账户登录失败，请联系管理员')
  } finally {
    quickLoginLoading.value = false
  }
}

/**
 * 自动填充记住的账号
 */
const autoFillRememberedAccount = () => {
  // 这里可以从localStorage中获取记住的账号信息
  const rememberedAccount = localStorage.getItem('remembered_account')
  if (rememberedAccount) {
    loginForm.account = rememberedAccount
    loginForm.rememberMe = true
  }
}

// 组件挂载时执行
onMounted(() => {
  autoFillRememberedAccount()
  
  // 如果已经登录，直接跳转到AI聊天页面
  if (authStore.isAuthenticated) {
    const redirect = (route.query.redirect as string) || '/chat'
    router.push(redirect)
  }
})
</script>

<style scoped>
/* 自定义样式 */
.el-form-item {
  margin-bottom: 20px;
}

.el-input {
  border-radius: 8px;
}

.el-button {
  border-radius: 8px;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .max-w-md {
    max-width: 100%;
    margin: 0 16px;
  }
  
  .bg-white {
    padding: 24px;
  }
}

/* 动画效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 输入框聚焦效果 */
.el-input:focus-within {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
  transition: all 0.2s ease;
}

/* 按钮悬停效果 */
.el-button--primary:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
  transition: all 0.2s ease;
}

/* 链接悬停效果 */
a {
  transition: all 0.2s ease;
}

a:hover {
  text-decoration: none;
}
</style>
